package 力扣_算法题综合.自己不会但觉得高频;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author zx
 * @create 2023-01-09 22:59
 */
public class 逆波兰表达式求值_150 {
    /**
     * @return 官方解法,但是代码随想录的动画演示好理解
     */
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i = 0;i < tokens.length;i++){
            String str = tokens[i];
            if(isNumber(str)){
                stack.push(Integer.parseInt(str));
            }else{
                //注意接收num的数值顺序与后面运算时num的顺序要对应,否则结果会出错
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch(str){
                    case "+":
                        stack.push(num1 + num2);
                        break;
                    case "-":
                        stack.push(num1 - num2);
                        break;
                    case "*":
                        stack.push(num1 * num2);
                        break;
                    case "/":
                        stack.push(num1 / num2);
                        break;
                    default:
                }
            }
        }
        return stack.pop();
    }
    private boolean isNumber(String s){
        return !("+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s));
    }
}
